<?php

namespace AppBundle\Controller;

use AdminBundle\Entity\HuobiAlertSender;
use AdminBundle\Entity\HuobiAlertTimestamp;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends HuobiBaseController
{

    /**
     * @Route("/klinealert", name="klinealert")
     */
    public function klineAction(Request $request)
    {
        // http://123.206.124.147:8082/ideal/klines/monitor
        // 定时请求地址，拉取警报数据
        return new Response('ok');
    }

    /**
     * @Route("/index", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.project_dir')) . DIRECTORY_SEPARATOR,
        ]);
    }

    /**
     * 终端显示页面
     * @Route("/track", name="huobi_calc_kline_1min_forward")
     */
    public function trackAction(Request $request)
    {
        $length = $request->query->getInt('length', 20);
        $duration = $request->query->getInt('duration', 720);

        return $this->redirectToRoute('huobi_calc_kline_1min_track', array('length' => $length, 'duration' => $duration));
    }

    /**
     * 邮件通知 delete on 2018-07-20 14:53
     */
    public function del_mailPushAction(Request $request)
    {
        $length = $request->query->getInt('length', 100);
        $duration = $request->query->getInt('duration', 0);
        $market = $request->query->get('market', 'huobi');
        $coin = $request->query->get('coin', '');

        $em = $this->getDoctrine()->getManager();

        // 取最后发送邮件通知的时间戳
        $alertTimestamp = $em->getRepository('AdminBundle:HuobiAlertTimestamp')->findOneBy(array('id' => 1));

        if (empty($alertTimestamp)) {
            $alertTimestamp = new HuobiAlertTimestamp();
        }
        $duration = (time() - $alertTimestamp->getTimeStamp()) / 60;
        // 取时间戳取之后新增满足条件的数据
        $options = ['length' => $length, 'duration' => $duration, 'coin' => $coin];

        // deleted on 2018-07-20 12:35:00
//        $data = $em->getRepository('AdminBundle:HuobiCalcKline1min')
//            ->getAmazing1_0($length, $duration, $coin, time());

        // added on 2018-07-20 12:35:00
        $service = 'app.task.alert_model1.0';
        $alert_model = $this->get($service);
        $data = $alert_model->process($options);

        if (empty($data)) {
            return $this->json(['code' => 1, 'message' => 'none amazing.', 'time' => time(),
                'data' => ['datetime' => $alertTimestamp->getCoinTime(),
                    'timestamp' => $alertTimestamp->getTimeStamp()]]);
        }
        // 更新最后发送邮件通知的时间戳
        $data0 = $data[0];
        $alertTimestamp->setTimeStamp(strtotime($data0['coinTime']))
            ->setCoinTime(new \DateTime($data0['coinTime']))
            ->setCtime(new \DateTime());
        $em->persist($alertTimestamp);
        $em->flush();

        // 格式化通知内容
        $subject = sprintf("[%s] %s",
            strtoupper(implode(',', array_column($data, 'coin'))),
            date('Y-m-d H:i:s')
        );

        $response = $this->render('default/track.html.twig', [
            'data' => $data,
        ]);

        // 发送邮件
        $result = $this->sendMail($subject, $response->getContent());

        return $this->json(['code' => 0, 'message' => 'ok', 'time' => time(), 'data' => $result]);
    }

    private function mailModel1_0($options = [])
    {
        $service = 'app.task.alert_model1.0';
        $alert_model = $this->get($service);
        $data = $alert_model->process($options);

        if (empty($data)) {
            return null;
        }

        // 格式化通知内容
        $subject = sprintf("[%s] %s",
            strtoupper(implode(',', array_column($data, 'coin'))),
            date('Y-m-d H:i:s')
        );

        $response = $this->render('default/track.html.twig', [
            'data' => $data,
            'title' => 'mail broadcast',
        ]);

        // 发送邮件
        $result = $this->sendMail($subject, $response->getContent());
        return $result;
    }

    private function mailModel6_0($options = [])
    {
        $service = 'app.task.alert_model6.0';
        $alert_model = $this->get($service);
        $data = $alert_model->process($options);

        if (empty($data)) {
            return null;
        }

        // 格式化通知内容
        $subject = sprintf("6.0 重要通知 [%s] %s",
            strtoupper(implode(',', array_column($data, 'coin'))),
            date('Y-m-d H:i:s')
        );

        $response = $this->render('default/track.html.twig', [
            'data' => $data,
            'title' => 'important',
        ]);
        $sender = ['addr' => '18025379@qq.com', 'name' => '客服:大成', 'password' => 'wdfzplrejuegcadg'];
        $recipients = ['84096437@qq.com', '834820099@qq.com',];
        // 发送邮件
        $result = self::mailFromQQTo($sender, $subject, $recipients, $response->getContent());

        return $result;
    }

    private function mailModel2_4($options = [])
    {
        $service = 'app.task.alert_model2.4';
        $alert_model = $this->get($service);
        $data = $alert_model->process($options);

        if (empty($data)) {
            return null;
        }

        // 格式化通知内容
        $subject = sprintf("2.4 重要通知 [%s] %s",
            strtoupper(implode(',', array_column($data, 'coin'))),
            date('Y-m-d H:i:s')
        );

        $response = $this->render('default/track.html.twig', [
            'data' => $data,
            'title' => 'important',
        ]);
        $sender = ['addr' => '18025379@qq.com', 'name' => '客服:大成', 'password' => 'wdfzplrejuegcadg'];
        $recipients = ['84096437@qq.com',];
        // 发送邮件
        $result = self::mailFromQQTo($sender, $subject, $recipients, $response->getContent());

        return $result;
    }

    /**
     * 邮件通知
     * @Route("/mailpush", name="huobi_kline_1min_amazing_mail")
     */
    public function mailPushAction(Request $request)
    {
        $length = $request->query->getInt('length', 100);
        $duration = $request->query->getInt('duration', 2);
        $market = $request->query->get('market', 'huobi');
        $coin = $request->query->get('coin', '');
        $time_stamp = $request->query->get('time_stamp', time() + 60);

        // 取时间戳取之后新增满足条件的数据
        $options = ['length' => $length, 'duration' => $duration, 'coin' => $coin, 'time_stamp' => $time_stamp];

        $result = $this->mailModel1_0($options) ?: 0;
//        $result += ($this->mailModel6_0($options) ?: 0);
//        $result = ($this->mailModel2_4($options) ?: 0);

        return $this->json(['code' => 0, 'message' => 'ok', 'time' => $options, 'data' => $result]);
    }
}
